
import requests
import json
import warnings
warnings.filterwarnings('ignore')

# 基础配置
BASE_URL = "http://test-newanlios88-znmz.rongmei.shuwen.com"

# 基础请求头 - 所有请求共用
BASE_HEADERS = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
    'Accept': 'application/json, text/plain, */*',
    'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
    'Accept-Encoding': 'gzip, deflate',
    'Connection': 'keep-alive',
}

def get_headers_with_auth(token=None, referer=None):
    """
    获取带有认证信息的请求头
    :param token: 认证token
    :param referer: 引用页面
    :return: 完整的请求头字典
    """
    headers = BASE_HEADERS.copy()
    headers.update({
        'Content-Type': 'application/json',
        'Origin': BASE_URL,
    })
    
    if referer:
        headers['Referer'] = BASE_URL + referer
    
    return headers

def test_login_with_authkey():
    """
    使用authKey和passwordx进行登录测试
    :return: 登录成功返回token，失败返回None
    """
    login_url = BASE_URL + "/web/uic/api/v2/login/enterprise/user_pw/v3"
    
    # 登录参数
    login_data = {
        "authKey": "admin",
        "passwordx": "8a7065ab7610cbb8f14f37bc22f96a5a"
    }
    
    # 获取登录请求头
    headers = get_headers_with_auth(referer='/login')
    
    print("🚀 开始登录测试...")
    print(f"📍 登录URL: {login_url}")
    print(f"🔑 authKey: {login_data['authKey']}")
    print(f"🔒 passwordx: {login_data['passwordx'][:8]}...")  # 只显示前8位保护密码
    print("-" * 60)
    
    try:
        # 发送POST登录请求
        response = requests.post(
            login_url,
            json=login_data,
            headers=headers,
            timeout=30,
            allow_redirects=True
        )
        
        print(f"📊 响应状态码: {response.status_code}")
        
        # 尝试解析JSON响应
        try:
            response_data = response.json()
            print(f"📄 响应数据: {json.dumps(response_data, ensure_ascii=False, indent=2)}")
            
            # 检查登录是否成功
            if response.status_code == 200:
                # 根据实际API的响应格式判断登录成功
                if response_data.get('code') == 0 or response_data.get('success') == True:
                    print("✅ 登录成功！")
                    
                    # 获取token或其他认证信息
                    if 'token' in response_data:
                        token = response_data['token']
                        print(f"🔑 Token: {token}")
                        return token
                        
                    elif 'data' in response_data:
                        print(f"📋 返回数据: {response_data['data']}")
                        return None
                        
                else:
                    error_msg = response_data.get('message', '未知错误')
                    print(f"❌ 登录失败: {error_msg}")
                    return None
                    
            else:
                print(f"❌ 登录请求失败，状态码: {response.status_code}")
                print(f"📄 响应内容: {response.text}")
                return None
                
        except json.JSONDecodeError:
            print("📄 响应内容（非JSON格式）:")
            print(response.text[:500])
            return None
            
    except requests.exceptions.Timeout:
        print("⏰ 请求超时")
        return None
    except requests.exceptions.ConnectionError as e:
        print(f"🔌 连接错误: {e}")
        return None
    except requests.exceptions.RequestException as e:
        print(f"❗ 请求异常: {e}")
        return None
    except Exception as e:
        print(f"💥 其他错误: {e}")
        return None

def user_message(token):
    """
    获取用户信息 - 使用变量传递的token
    :param token: 认证token
    """
    user_message_url = BASE_URL + "/web/uic/api/v2/account/info"
    
    if not token:
        print("❌ 未提供token，请先运行登录测试")
        return
    
    # 获取用户信息请求头
    headers = get_headers_with_auth(token=token, referer='/app')
    # 添加cookie信息
    headers['Cookie'] = '_sw_envid=m3F19lHQggUBAQrgAAFA2bsy; _sw_token=05C7043495D21EBAAC9D3A26703F9EB0'
    
    print("🔍 开始获取用户信息...")
    print(f"📍 用户信息URL: {user_message_url}")
    print(f"🔑 使用Token: {token[:20]}...")  # 只显示前20位
    print("-" * 60)
    
    try:
        response = requests.get(user_message_url, headers=headers, timeout=30)
        print(f"📊 响应状态码: {response.status_code}")
        
        if response.status_code == 200:
            try:
                user_data = response.json()
                print("✅ 用户信息获取成功！")
                # 直接输出完整的JSON数据
                print(f"📋 用户信息JSON: {json.dumps(user_data, ensure_ascii=False, indent=2)}")
                return user_data
                        
            except json.JSONDecodeError:
                print("📄 响应内容（非JSON格式）:")
                print(response.text[:500])
                return None
        else:
            print(f"❌ 获取用户信息失败，状态码: {response.status_code}")
            print(f"📄 响应内容: {response.text[:200]}")
            return None
            
    except requests.exceptions.Timeout:
        print("⏰ 请求超时")
        return None
    except requests.exceptions.ConnectionError as e:
        print(f"🔌 连接错误: {e}")
        return None
    except requests.exceptions.RequestException as e:
        print(f"❗ 请求异常: {e}")
        return None
    except Exception as e:
        print(f"💥 其他错误: {e}")
        return None

if __name__ == '__main__':
    # 先进行登录测试
    print("=" * 60)
    print("🔐 第一步：登录测试")
    print("=" * 60)
    token = test_login_with_authkey()
    
    if token:
        print("\n" + "=" * 60)
        print("👤 第二步：获取用户信息")
        print("=" * 60)
        user_message(token)
    
    print("\n✅ 所有操作完成！")